package com.cgmnx.admin.web.controller.sys;

import com.cgmnx.admin.biz.sys.FileUploadBiz;
import com.cgmnx.admin.common.bean.ApiRes;
import com.cgmnx.admin.common.bean.CurrentUserInfo;
import com.cgmnx.admin.common.bean.UserContext;
import com.cgmnx.admin.common.constants.WebConstant;
import com.cgmnx.admin.common.exception.Preconditions;
import com.cgmnx.admin.dao.entity.sys.UpdFileEntity;
import com.cgmnx.admin.service.sys.UpdFileService;
import com.cgmnx.admin.service.sys.impl.OssFileUploadService;
import com.cgmnx.admin.web.model.MultiFileBucket;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Slf4j
@Controller
public class FileUploadController {

    private static final List<String> IMAGE_SUFFIX = Lists.newArrayList ( "png", "jpg", "gif", "jpeg" );

    private static final long MAX_SIZE_OF_UPLOAD_FILE = 10 * 1024 * 1024;

    @Resource
    private FileUploadBiz fileUploadBiz;

    @Autowired
    private UpdFileService updFileService;

    @Autowired
    private OssFileUploadService ossFileUploadService;

    @RequestMapping(value = "/cgmnx/file/upload.json", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes upload(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {

        Preconditions.checkNotNull ( file, "上传文件时，传入的文件为空" );

        // 校验上传文件的合法性
        if (file.isEmpty ()) {
            return ApiRes.returnFail ( "上传的文件为空" );
        }
        if (file.getSize () > MAX_SIZE_OF_UPLOAD_FILE) {
            return ApiRes.returnFail ( "上传的文件过大" );
        }
        String optional = ossFileUploadService.upload ( file.getOriginalFilename(), file.getInputStream () );

        return ApiRes.returnSuccess ( optional );

    }

    @RequestMapping(value = "/cgmnx/file/multiUpload.json", method = RequestMethod.POST)
    public ApiRes multiFileUpload(MultiFileBucket multiFileBucket, BindingResult result, ModelMap model) throws IOException {

        String userName = WebConstant.CURRENT_LOGIN_USER;
        CurrentUserInfo userInfo = UserContext.getUserInfo ();
        if (userInfo != null) {
            userName = userInfo.getUserId ();
        }

        List<String> fileNames = Lists.newArrayList ();

        //Now do something with file...
        for (MultipartFile file : multiFileBucket.getFiles ()) {

            String md5DigestAsHex = DigestUtils.md5DigestAsHex ( file.getInputStream () );

            UpdFileEntity updFileEntity = updFileService.queryByEncryptName ( md5DigestAsHex );

            if (updFileEntity == null) {


                Optional<UpdFileEntity> optional = fileUploadBiz.upload ( file.getOriginalFilename (), file.getInputStream (),
                        file.getSize (), userName, md5DigestAsHex );

                if (optional.isPresent ()) {
                    fileNames.add ( file.getOriginalFilename () );
                } else {
                    log.error ( "文件上传失败，文件名：{}", file.getOriginalFilename () );
                }
            } else {
                log.error ( "文件已经存在，文件名：{}", file.getOriginalFilename () );
            }
        }

        return ApiRes.list ( fileNames );
    }
}

